<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-input v-model="queryParams.customerCode" placeholder="客户编码" style="width: 150px; margin-right: 10px;" />
    <el-input v-model="queryParams.customerName" placeholder="客户名称" style="width: 150px; margin-right: 10px;" />
    <el-button @click="fetchData">查询</el-button>

    <!-- 表格展示汇总数据 应收报表汇总-->
    <h3></h3>
    <el-table :data="list" border style="width: 100%">
      <el-table-column prop="customerCode" label="客户编码" align="center"></el-table-column>
      <el-table-column prop="customerName" label="客户名称" align="center"></el-table-column>

      <!-- 应收金额 -->
      <el-table-column
          prop="receivableAmount"
          label="应收金额"
          :show-overflow-tooltip="true">
        <template #default="{ row }">
          <a href="javascript:void(0);" @click="showDetails(row.customerCode)" class="highlight-text">
            {{ row.receivableAmount ? row.receivableAmount.toFixed(2) : '0.00' }}
          </a>
        </template>
      </el-table-column>

      <!-- 已收金额 -->
      <el-table-column label="已收金额" prop="receivedAmount">
        <template #default="{ row }">
          <a href="javascript:void(0);" @click="showReceiptDetails(row.customerCode)" class="highlight-text">
            {{ row.receivedAmount ? row.receivedAmount.toFixed(2) : '0.00' }}
          </a>
        </template>
      </el-table-column>

      <!-- 未收金额 -->
      <el-table-column prop="unReceivedAmount" label="未收金额" >
        <template #default="{ row }">
          {{ row.unReceivedAmount ? row.unReceivedAmount.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        style="margin-top: 20px;"
    />

    <!-- 弹窗 - 应收明细 -->
    <el-dialog :visible.sync="dialogVisible" title="客户明细信息" width="90%" top="5vh">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">

        <!-- 应收数据流 -->
        <el-tab-pane label="应收数据流" name="dataStream">
          <el-table :data="dataStreamList" border style="width: 100%">
            <el-table-column prop="inOutCode" label="出入库编码" align="center" />
            <el-table-column prop="receivableAmount" label="应收金额" align="right" />
            <el-table-column prop="orderDate" label="订单日期" align="center" />
            <el-table-column prop="dataType" label="数据类型" align="center" />
            <el-table-column prop="customerCode" label="客户编码" align="center" />
            <el-table-column prop="customerName" label="客户名称" align="center" />
            <el-table-column prop="productName" label="产品名称" align="center" />
            <el-table-column prop="productCode" label="产品编码" align="center" />
            <el-table-column prop="productType" label="产品类型" align="center" />
            <el-table-column prop="productAttribute" label="产品属性" align="center" />
            <el-table-column prop="specification" label="规格型号" align="center" />
            <el-table-column prop="salesQuantityRequired" label="销售数量需求" align="center" />
            <el-table-column prop="deliveryQuantity" label="发货出库数" align="center" />
          </el-table>
          <!-- <p v-if="dataStreamList.length === 0" style="text-align:center;">暂无应收数据流信息</p> -->
          <div class="summary-line">应收金额汇总：{{ receivableDataStreamTotal.toFixed(2) }} 元</div>
        </el-tab-pane>

        <!-- 云仓销售明细 -->
        <el-tab-pane label="云仓销售明细" name="salesDetail">
          <el-table :data="salesDetailList" border style="width: 100%">
            <el-table-column prop="yuncangSalesCode" label="云仓销售单" align="center" />
            <el-table-column prop="goodsAmount" label="产品金额" align="right" />
            <el-table-column prop="orderDate" label="订单日期" align="center" />
            <el-table-column prop="cus" label="客户名称" align="center" />
            <el-table-column prop="cusCode" label="客户编码" align="center" />
            <el-table-column prop="goodsName" label="产品名称" align="center" />
            <el-table-column prop="goodsNo" label="产品编码" align="center" />
            <el-table-column prop="goodsCount" label="销售数量" align="center" />
            <el-table-column prop="goodsType" label="产品类型" align="center" />
            <el-table-column prop="specName" label="规格型号" align="center" />
          </el-table>
          <!-- <p v-if="salesDetailList.length === 0" style="text-align:center;">暂无云仓销售明细信息</p> -->
           <div class="summary-line">产品金额汇总：{{ salesDetailTotal.toFixed(2) }} 元</div>
        </el-tab-pane>

        <!-- 退款确认单 -->
        <el-tab-pane label="退款确认单" name="refundOrder">
          <el-table :data="refundOrderList" border style="width: 100%">
            <el-table-column prop="bxCode" label="退款单编码" align="center" />
            <el-table-column prop="bxDate" label="退款日期" align="center" />
            <el-table-column prop="bxFkyy" label="退款类型" align="center" />
            <el-table-column prop="afterSaleDeductionAmount" label="售后抵扣金额" align="right" />
            <el-table-column prop="customerCode" label="客户编码" align="center" />
            <el-table-column prop="customerName" label="客户名称" align="center" />
            <el-table-column prop="remark" label="备注" align="center" />
          </el-table>
          <!-- <p v-if="refundOrderList.length === 0" style="text-align:center;">暂无退款确认单信息</p> -->
           <div class="summary-line">售后抵扣金额汇总：{{ refundDeductionTotal.toFixed(2) }} 元</div>
        </el-tab-pane>

        <!-- 云仓退货明细 -->
        <el-tab-pane label="云仓退货明细" name="returnDetail">
          <el-table :data="returnDetailList" border style="width: 100%">
            <el-table-column prop="yuncangCode" label="云仓退货单" align="center" />
            <el-table-column prop="returnDate" label="退货日期" align="center" />
            <el-table-column prop="cus" label="客户名称" align="center" />
            <el-table-column prop="cusCode" label="客户编码" align="center" />
            <el-table-column prop="orderDate" label="订单日期" align="center" />
            <el-table-column prop="itemName" label="产品名称" align="center" />
            <el-table-column prop="itemCode" label="产品编码" align="center" />
            <el-table-column prop="orderNum" label="订单数量" align="center" />
            <el-table-column prop="returnNum" label="退货数量" align="center" />
            <el-table-column prop="itemType" label="产品类型" align="center" />
            <el-table-column prop="itemSpec" label="规格型号" align="center" />
          </el-table>
          <!-- <p v-if="returnDetailList.length === 0" style="text-align:center;">暂无云仓退货明细信息</p> -->
           <div class="summary-line">退货金额汇总：{{ returnDetailTotal.toFixed(2) }} 元</div>
        </el-tab-pane>

      </el-tabs>
    </el-dialog>

    <!-- 弹窗 - 收款 & 退款明细 -->
    <el-dialog :visible.sync="receiptDialogVisible" title="已收金额明细" width="90%" top="5vh">
      <el-tabs v-model="activeTab1" @tab-click="receiptDetailsHandleTabClick">
        <!-- 收款确认单 -->
        <el-tab-pane label="收款确认单" name="confirmOrder">
          <el-table :data="confirmOrderList" border style="width: 100%">
            <el-table-column prop="skCode" label="收款单编码"></el-table-column>
            <el-table-column prop="skJe" label="收款金额" align="right"></el-table-column>
            <el-table-column prop="skDate" label="收款日期" align="center"></el-table-column>
            <el-table-column prop="skLx" label="收款类型" align="center"></el-table-column>
            <el-table-column prop="skListCode" label="产品编码" align="center"></el-table-column>
            <el-table-column prop="skListName" label="产品名称" align="center"></el-table-column>
            <el-table-column prop="skListNum" label="零售数量" align="center"></el-table-column>
            <el-table-column prop="skKhCode" label="客户编码" align="center"></el-table-column>
            <el-table-column prop="skKh" label="客户名称" align="center"></el-table-column>
          </el-table>
          <!-- <p v-if="confirmOrderList.length === 0" style="text-align:center;">暂无收款确认单信息</p> -->
           <div class="summary-line">收款金额汇总：{{ confirmOrderTotal.toFixed(2) }} 元</div>
        </el-tab-pane>

        <!-- 退款确认单 -->
        <el-tab-pane label="退款确认单"  name="confirmRefundOrder">
          <el-table :data="refundOrderList" border style="width: 100%">
            <el-table-column prop="bxCode" label="退款单编码" align="center"></el-table-column>
            <el-table-column prop="refundReceivedAmount" label="退回收款金额" align="right"></el-table-column>
            <el-table-column prop="bxDate" label="退款日期" align="center"></el-table-column>
            <el-table-column prop="bxFkyy" label="退款原因/类型" align="center"></el-table-column>
            <el-table-column prop="customerCode" label="客户编码" align="center"></el-table-column>
            <el-table-column prop="customerName" label="客户名称" align="center"></el-table-column>
            <el-table-column prop="remark" label="备注" align="center"></el-table-column>
          </el-table>
          <!-- <p v-if="refundOrderList.length === 0" style="text-align:center;">暂无退款确认单信息</p> -->
           <div class="summary-line">退回收款金额汇总：{{ refundOrderReceivedTotal.toFixed(2) }} 元</div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  getReceivableSummary,
  getReceivableDataStream,
  getSalesDetailByCustomerCode,
  getRefundOrderByCustomerCode,
  getReturnDetailByCustomerCode,
  getConfirmOrderByCustomerCode
} from "@/api/mes/md/receivableReport";

export default {
  name: "ReceivableReport",
  data() {
    return {
      list: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      queryParams: {
        customerCode: '',
        customerName: ''
      },
      dialogVisible: false,
      receiptDialogVisible: false,
      activeTab: 'dataStream',
      activeTab1: 'confirmOrder',
      currentCustomerCode: '',

      // 存储四个接口的数据
      dataStreamList: [],
      salesDetailList: [],
      refundOrderList: [],
      returnDetailList: [],
      confirmOrderList: [],
      receivableTotal: 0,       // 应收金额汇总
      goodsAmountTotal: 0,      // 产品金额汇总
      deductionTotal: 0,        // 售后抵扣金额汇总
      returnAmountTotal: 0,     // 退货金额汇总
      receivedAmountTotal: 0,   // 收款金额汇总
      refundReceivedTotal: 0    // 退回收款金额汇总
    };
  },
  created() {
    this.fetchData();
  },
  computed: {
    // 应收数据流汇总
    receivableDataStreamTotal() {
      return (this.dataStreamList || []).reduce((sum, item) => sum + (item.receivableAmount || 0), 0);
    },

    // 云仓销售明细汇总
    salesDetailTotal() {
      return (this.salesDetailList || []).reduce((sum, item) => sum + (item.goodsAmount || 0), 0);
    },

    // 退款确认单售后抵扣金额汇总
    refundDeductionTotal() {
      return (this.refundOrderList || []).reduce((sum, item) => sum + (item.afterSaleDeductionAmount || 0), 0);
    },

    // 云仓退货明细退货金额汇总
    returnDetailTotal() {
      return (this.returnDetailList || []).reduce((sum, item) => sum + (item.returnAmout || 0), 0);
    },

    // 收款确认单收款金额汇总
    confirmOrderTotal() {
      return (this.confirmOrderList || []).reduce((sum, item) => sum + (item.skJe || 0), 0);
    },

    // 退款确认单退回收款金额汇总
    refundOrderReceivedTotal() {
      return (this.refundOrderList || []).reduce((sum, item) => sum + (item.refundReceivedAmount || 0), 0);
    }
  },

  methods: {
    fetchData(pageNum = 1) {
      const params = {
        pageNum,
        pageSize: this.pageSize,
        customerCode: this.queryParams.customerCode,
        customerName: this.queryParams.customerName
      };
      getReceivableSummary(params).then(response => {
        if (response.code === 200) {
          this.list = response.data.list || [];
          this.total = response.data.total || 0;
        }
      });
    },

    handleCurrentChange(pageNum) {
      this.currentPage = pageNum;
      this.fetchData(pageNum);
    },

    showDetails(customerCode) {
      this.currentCustomerCode = customerCode;
      this.dialogVisible = true;
      this.activeTab = 'dataStream';

      // 清空旧数据以确保重新加载
      this.dataStreamList = [];
      this.salesDetailList = [];
      this.refundOrderList = [];
      this.returnDetailList = [];

      this.handleTabClick({ name: 'dataStream' });
    },

    showReceiptDetails(customerCode) {
      this.currentCustomerCode = customerCode;
      this.receiptDialogVisible = true;
      this.activeTab1 = 'confirmOrder';
      console.log("this.activeTab1>>>>>>>",this.activeTab1)
      // 清空旧数据以确保重新加载
      this.confirmOrderList = [];
      this.refundOrderList = [];

      this.$nextTick(() => {
        this.receiptDetailsHandleTabClick({ name: 'confirmOrder' });
      });
    },

    handleTabClick(tab) {
      const code = this.currentCustomerCode;
      if (!code) return;

      const tabName = tab.name;

      switch (tabName) {
        case 'dataStream':
          if (this.dataStreamList.length > 0 && this.currentCustomerCode === code) return;
          getReceivableDataStream({ customerCode: code }).then(res => {
             // 按照 orderDate 倒序排序
             this.dataStreamList = (res.data || []).sort((a, b) => {
                return new Date(b.orderDate) - new Date(a.orderDate);
              });
          });
          break;
        case 'salesDetail':
          if (this.salesDetailList.length > 0 && this.currentCustomerCode === code) return;
          getSalesDetailByCustomerCode({ customerCode: code }).then(res => {
             // 按照 orderDate 倒序排序
             this.salesDetailList = (res.data || []).sort((a, b) => {
                return new Date(b.orderDate) - new Date(a.orderDate);
              });
          });
          break;
        case 'refundOrder':
          if (this.refundOrderList.length > 0 && this.currentCustomerCode === code) return;
          getRefundOrderByCustomerCode({ customerCode: code }).then(res => {
            // 按照 bxDate 倒序排序
            this.refundOrderList = (res.data || []).sort((a, b) => {
               return new Date(b.bxDate) - new Date(a.bxDate);
             });
          });
          break;
        case 'returnDetail':
          if (this.returnDetailList.length > 0 && this.currentCustomerCode === code) return;
          getReturnDetailByCustomerCode({ customerCode: code }).then(res => {
            // 按照 returnDate 倒序排序
            this.returnDetailList = (res.data || []).sort((a, b) => {
               return new Date(b.returnDate) - new Date(a.returnDate);
             });
          });
          break;
      }
    },

    receiptDetailsHandleTabClick(tab) {
      const code = this.currentCustomerCode;
      if (!code) return;

      const tabName = tab.name;

      switch (tabName) {
        case 'confirmOrder': // 收款确认单 tab
          if (this.confirmOrderList.length > 0 && this.currentCustomerCode === code) return;
          getConfirmOrderByCustomerCode({ customerCode: code }).then(res => {
            // 按照 skDate 倒序排序
            this.confirmOrderList = (res.data || []).sort((a, b) => {
               return new Date(b.skDate) - new Date(a.skDate);
             });
          });
          break;

        case 'refundOrder1': // 退款确认单 tab
          if (this.refundOrderList.length > 0 && this.currentCustomerCode === code) return;
          getRefundOrderByCustomerCode({ customerCode: code }).then(res => {
            // 按照 bxDate 倒序排序
            this.refundOrderList = (res.data || []).sort((a, b) => {
               return new Date(b.bxDate) - new Date(a.bxDate);
             });
          });
          break;
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.highlight-text {
  font-weight: bold;
  color: #409EFF;
  background-color: #ecf5ff;
  padding: 2px 5px;
  border-radius: 3px;
  cursor: pointer;
}
</style>
